<script setup lang="ts">
import { ref, computed, onMounted, h } from 'vue'
import {
  Button,
  Card,
  Table,
  Modal,
  Form,
  Input,
  message,
  Space,
  Select,
  Tag,
  Cascader
} from 'ant-design-vue'
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
  ReloadOutlined,
  KeyOutlined
} from '@ant-design/icons-vue'
import type { TableColumnsType } from 'ant-design-vue'
import type { Teacher } from '@/types/teacher'
import { teacherApi } from '@/api/modules/teacher'
import { organizationApi } from '@/api/modules/organization'
import type { Organization } from '@/types/organization'
import type { Rule } from 'ant-design-vue/es/form'
import ClassSelect from '@/components/business/ClassSelect.vue'
import dayjs from 'dayjs'

// 组织类型定义
const organizationType = {
  COLLEGE: 1,
  MAJOR: 2,
  CLASS: 3
} as const

// 页面加载状态
const loading = ref(false)
const classLoading = ref(false)

// 班级数据
interface CascaderOption {
  value: number
  label: string
  children?: CascaderOption[]
}

const classOptions = ref<CascaderOption[]>([])

// 表格数据
const tableData = ref<Teacher[]>([])
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: (total: number) => `共 ${total} 条记录`,
  showSizeChanger: true,
  pageSizeOptions: ['10', '20', '30', '50'],
  // 自定义页码选项的文本
  buildOptionText: (opt: { value: number }) => {
    return `${opt.value} 条/页`
  }
})

// 添加性别选项
const genderOptions = [
  { label: '未知', value: 0 },
  { label: '男', value: 1 },
  { label: '女', value: 2 }
]

// 表单数据
interface TeacherForm {
  id?: number
  userCode: string
  realName: string
  gender: number      // 新增性别字段
  phone?: string
  email?: string
  classIds: number[]
  position?: string
}

const formRef = ref()
const formState = ref<TeacherForm>({
  userCode: '',
  realName: '',
  gender: 0,         // 默认未知
  phone: '',
  email: '',
  classIds: [],
  position: ''
})

// 弹窗控制
const modalVisible = ref(false)
const modalTitle = ref('新增教师')
const modalLoading = ref(false)

// 搜索表单
interface SearchForm {
  userCode?: string
  realName?: string
  phone?: string
  classIds?: number[]
}

const searchForm = ref<SearchForm>({})

// 表格列配置
const columns: TableColumnsType = [
  {
    title: '工号',
    dataIndex: 'username',
    width: 120,
    align: 'center',
    key: 'username'
  },
  {
    title: '姓名',
    dataIndex: 'realName',
    width: 120,
    align: 'center',
    key: 'realName'
  },
  {
    title: '手机号',
    dataIndex: 'phone',
    width: 150,
    align: 'center',
    key: 'phone'
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    align: 'center',
    key: 'email'
  },
  {
    title: '负责班级',
    dataIndex: 'classes',
    align: 'center',
    width: 300,
    key: 'classes',
    customRender: ({ text: classes }) => {
      if (!classes?.length) return '-'
      return h('div', { style: { display: 'flex', flexDirection: 'column', gap: '4px' } }, 
        classes.map(c => 
          h(Tag, { 
            color: 'blue',
            style: { margin: 0 }  // 覆盖 Tag 默认的 margin
          }, () => 
            `${c.collegeName} / ${c.majorName} / ${c.name}`
          )
        )
      )
    }
  },
  {
    title: '职位',
    dataIndex: 'position',
    align: 'center',
    width: 120,
    key: 'position'
  },
  {
    title: '性别',
    dataIndex: 'gender',
    align: 'center',
    width: 80,
    customRender: ({ text }) => {
      const gender = genderOptions.find(item => item.value === text)
      return gender ? gender.label : '未知'
    }
  },
  {
    title: '状态',
    dataIndex: 'status',
    align: 'center',
    width: 100,
    key: 'status',
    customRender: ({ text, record }) => h(Tag, {
      color: text ? 'success' : 'error',
      style: { cursor: 'pointer' },
      onClick: () => handleStatusChange(record)
    }, {
      default: () => text ? '启用' : '禁用'
    })
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    align: 'center',
    width: 180,
    key: 'createTime',
    customRender: ({ text }) => {
      return text ? dayjs(text).format('YYYY-MM-DD HH:mm:ss') : '-'
    }
  },
  {
    title: '操作',
    key: 'action',
    align: 'center',
    width: 180,
    fixed: 'right',
    slots: { customRender: 'action' }
  }
]

// 获取所有班级
const getAllClasses = async () => {
  classLoading.value = true
  try {
    const data = await organizationApi.getTree()
    
    // 转换为级联选择需要的数据结构，搜索框不需要禁用节点
    const convertToOptions = (items: Organization[]): CascaderOption[] => {
      return items.map(item => ({
        value: item.id,
        label: item.name,
        children: item.children ? convertToOptions(item.children) : undefined,
        // 移除 disabled 属性
        isLeaf: item.type === organizationType.CLASS
      }))
    }
    
    classOptions.value = convertToOptions(data || [])
  } catch (error) {
    console.error('获取班级列表失败:', error)
    message.error(error||'获取班级列表失败')
  } finally {
    classLoading.value = false
  }
}

// 获取教师列表
const getTeacherList = async () => {
  loading.value = true
  try {
    // 获取选中节点的所有班级ID
    const getClassIds = (selectedPath?: number[]) => {
      // 如果没有选择任何节点，返回undefined
      if (!selectedPath?.length) return undefined

      const lastNode = selectedPath[selectedPath.length - 1]
      
      // 找到对应的节点
      let node = classOptions.value.find(n => n.value === selectedPath[0])
      for (let i = 1; i < selectedPath.length; i++) {
        node = node?.children?.find(n => n.value === selectedPath[i])
      }
      
      if (!node) return undefined

      const classIds: number[] = []
      
      // 如果是班级节点，直接返回
      if (node.isLeaf) {
        return String(lastNode)
      }
      
      // 如果是学院或专业节点，获取其下所有班级
      const getAllClassIds = (item?: CascaderOption) => {
        if (!item) return
        if (item.isLeaf) {
          classIds.push(item.value)
        } else if (item.children) {
          item.children.forEach(getAllClassIds)
        }
      }
      
      getAllClassIds(node)
      return classIds.length ? classIds.join(',') : undefined
    }

    const data = await teacherApi.getTeacherPage({
      ...searchForm.value,
      classIds: getClassIds(searchForm.value.classIds),
      page: pagination.value.current - 1,
      size: pagination.value.pageSize
    })
    
    tableData.value = data.content
    pagination.value.total = data.totalElements
  } catch (error) {
    console.error('获取教师列表失败:', error)
    message.error(error||'获取教师列表失败')
  } finally {
    loading.value = false
  }
}

// 新增教师
const handleAdd = () => {
  formState.value = {
    userCode: '',
    realName: '',
    gender: 0,
    phone: '',
    email: '',
    classIds: [],
    position: ''
  }
  modalTitle.value = '新增教师'
  modalVisible.value = true
}

// 编辑教师
const handleEdit = async (record: Teacher) => {
  try {
    const teacherInfo = await teacherApi.getById(record.id)
    formState.value = {
      id: teacherInfo.id,
      userCode: teacherInfo.username,
      realName: teacherInfo.realName,
      gender: teacherInfo.gender || 0,  // 添加性别字段
      phone: teacherInfo.phone || '',
      email: teacherInfo.email || '',
      classIds: teacherInfo.classes?.map(c => c.id) || [],
      position: teacherInfo.position || ''
    }
    modalTitle.value = '编辑教师'
    modalVisible.value = true
  } catch (error) {
    console.error('获取教师详情失败:', error)
    message.error(error||'获取教师详情失败')
  }
}

// 删除教师
const handleDelete = (record: Teacher) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除教师"${record.realName}"吗？`,
    okText: '确认',
    okType: 'danger',
    cancelText: '取消',
    async onOk() {
      try {
        await teacherApi.delete(record.id)
        message.success('删除成功')
        getTeacherList()
      } catch (error) {
        console.error('删除失败:', error)
        message.error(error||'删除失败')
      }
    }
  })
}

// 更新教师状态
const handleStatusChange = (record: Teacher) => {
  Modal.confirm({
    title: '确认操作',
    content: `确定要${record.status ? '禁用' : '启用'}教师"${record.realName}"吗？`,
    okText: '确认',
    cancelText: '取消',
    async onOk() {
      try {
        await teacherApi.updateStatus(record.id, !record.status)
        message.success('操作成功')
        getTeacherList()
      } catch (error) {
        console.error('操作失败:', error)
        message.error(error||'操作失败')
      }
    }
  })
}

// 重置密码
const handleResetPassword = (record: Teacher) => {
  Modal.confirm({
    title: '确认重置密码',
    content: `确定要重置教师"${record.realName}"的密码吗？重置后密码将变为工号。`,
    okText: '确认',
    cancelText: '取消',
    async onOk() {
      try {
        await teacherApi.resetPassword(record.id)
        message.success('密码重置成功')
      } catch (error) {
        console.error('密码重置失败:', error)
        message.error(error||'密码重置失败')
      }
    }
  })
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    modalLoading.value = true
    
    if (formState.value.id) {
      await teacherApi.update(formState.value.id, {
        userCode: formState.value.userCode,
        realName: formState.value.realName,
        gender: formState.value.gender,
        phone: formState.value.phone,
        email: formState.value.email,
        classIds: formState.value.classIds,
        position: formState.value.position
      })
      message.success('更新成功')
    } else {
      await teacherApi.create({
        userCode: formState.value.userCode,
        realName: formState.value.realName,
        gender: formState.value.gender,
        phone: formState.value.phone,
        email: formState.value.email,
        classIds: formState.value.classIds,
        position: formState.value.position
      })
      message.success('创建成功')
    }
    
    modalVisible.value = false
    getTeacherList()
  } catch (error) {
    console.error('提交失败:', error)
    message.error(error||'提交失败')
  } finally {
    modalLoading.value = false
  }
}

// 表单验证规则
const formRules: Record<string, Rule[]> = {
  userCode: [{ required: true, message: '请输入工号' }],
  realName: [{ required: true, message: '请输入姓名' }],
  gender: [{ required: true, message: '请选择性别' }],
  phone: [{ 
    pattern: /^1[3-9]\d{9}$/, 
    message: '请输入正确的手机号',
    transform: (value: string) => value?.trim()
  }],
  email: [{ 
    type: 'email', 
    message: '请输入正确的邮箱地址',
    transform: (value: string) => value?.trim()
  }]
}

// 初始化
onMounted(() => {
  getAllClasses()
  getTeacherList()
})

// 修改表格分页变更处理
const handleTableChange = (pag: any) => {
  pagination.value.current = pag.current
  pagination.value.pageSize = pag.pageSize
  getTeacherList()
}

// 处理搜索
const handleSearch = () => {
  pagination.value.current = 1
  getTeacherList()
}

// 重置搜索
const handleReset = () => {
  searchForm.value = {
    userCode: undefined,
    realName: undefined,
    phone: undefined,
    classIds: undefined
  }
  pagination.value.current = 1
  getTeacherList()
}
</script>

<template>
  <div class="teacher-page">
    <Card>
      <template #title>教师管理</template>
      <template #extra>
        <Button type="primary" @click="handleAdd">
          <template #icon><PlusOutlined /></template>
          新增教师
        </Button>
      </template>

      <!-- 搜索表单 -->
      <Form layout="inline" class="search-form">
        <Form.Item label="工号">
          <Input
            v-model:value="searchForm.userCode"
            placeholder="请输入工号"
            allow-clear
            @keyup.enter="handleSearch"
          />
        </Form.Item>
        <Form.Item label="姓名">
          <Input
            v-model:value="searchForm.realName"
            placeholder="请输入姓名"
            allow-clear
            @keyup.enter="handleSearch"
          />
        </Form.Item>
        <Form.Item label="手机号">
          <Input
            v-model:value="searchForm.phone"
            placeholder="请输入手机号"
            allow-clear
            @keyup.enter="handleSearch"
          />
        </Form.Item>
        <Form.Item label="负责班级">
          <Cascader
            v-model:value="searchForm.classIds"
            :options="classOptions"
            :loading="classLoading"
            placeholder="请选择班级"
            :show-search="true"
            :field-names="{ label: 'label', value: 'value', children: 'children' }"
            :change-on-select="true"
            style="min-width: 300px"
            :get-popup-container="triggerNode => triggerNode.parentNode"
          />
        </Form.Item>
        <Form.Item>
          <Space>
            <Button type="primary" @click="handleSearch">
              <template #icon><SearchOutlined /></template>
              查询
            </Button>
            <Button @click="handleReset">
              <template #icon><ReloadOutlined /></template>
              重置
            </Button>
          </Space>
        </Form.Item>
      </Form>

      <Table
        :loading="loading"
        :columns="columns"
        :data-source="tableData"
        :pagination="pagination"
        @change="handleTableChange"
      >
        <template #action="{ record }">
          <Space>
            <Button type="link" @click="handleEdit(record)">
              <template #icon><EditOutlined /></template>
              编辑
            </Button>
            <Button type="link" @click="handleResetPassword(record)">
              <template #icon><KeyOutlined /></template>
              重置密码
            </Button>
            <Button type="link" danger @click="handleDelete(record)">
              <template #icon><DeleteOutlined /></template>
              删除
            </Button>
          </Space>
        </template>
      </Table>
    </Card>

    <!-- 新增/编辑弹窗 -->
    <Modal
      :title="modalTitle"
      :maskClosable="false"
      :open="modalVisible"
      :confirm-loading="modalLoading"
      @ok="handleSubmit"
      @cancel="modalVisible = false"
      ok-text="确定",
      cancel-text="取消"
    >
      <Form
        ref="formRef"
        :model="formState"
        :rules="formRules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <Form.Item label="工号" name="userCode" :rules="formRules.userCode">
          <Input
            v-model:value="formState.userCode"
            placeholder="请输入工号"
            :disabled="!!formState.id"
          />
        </Form.Item>

        <Form.Item label="姓名" name="realName" :rules="formRules.realName">
          <Input v-model:value="formState.realName" placeholder="请输入姓名" />
        </Form.Item>

        <Form.Item label="性别" name="gender" :rules="formRules.gender">
          <Select
            v-model:value="formState.gender"
            placeholder="请选择性别"
            :options="genderOptions"
          />
        </Form.Item>

        <Form.Item label="手机号" name="phone" :rules="formRules.phone">
          <Input 
            v-model:value="formState.phone" 
            placeholder="请输入手机号"
            @blur="e => formState.phone = e.target.value.trim()"
          />
        </Form.Item>

        <Form.Item label="邮箱" name="email" :rules="formRules.email">
          <Input 
            v-model:value="formState.email" 
            placeholder="请输入邮箱"
            @blur="e => formState.email = e.target.value.trim()"
          />
        </Form.Item>

        <Form.Item label="负责班级">
          <ClassSelect v-model:value="formState.classIds" />
        </Form.Item>

        <Form.Item label="职位" name="position">
          <Input v-model:value="formState.position" placeholder="请输入职位" />
        </Form.Item>
      </Form>
    </Modal>
  </div>
</template>

<style lang="less" scoped>
.teacher-page {
  :deep(.ant-card-body) {
    padding: 24px;
  }

  .search-form {
    margin-bottom: 24px;
    padding: 24px;
    background: #fafafa;
    border-radius: 2px;

    :deep(.ant-form-item) {
      margin-bottom: 16px;
      
      &:last-child {
        margin-bottom: 0;
        margin-right: 0;
      }
    }

    // 修改级联选择的样式
    :deep(.ant-cascader-picker) {
      &.ant-cascader-picker-multiple {
        .ant-cascader-input {
          min-height: 32px;
          height: auto;
        }
      }
    }
  }

  :deep(.ant-tag) {
    &[role="button"] {
      cursor: pointer;
      
      &:hover {
        opacity: 0.8;
      }
    }
  }
}
</style> 